/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * TimeSpanPanel.java
 *
 * Created on 24.11.2011, 10:25:41
 */
package nl.fontys.sofa.odr.odrvpplugin.dialog;

import com.vp.plugin.ApplicationManager;
import com.vp.plugin.view.IDialog;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.SpinnerDateModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import nl.rug.search.odr.ws.dto.IterationDTO;

/**
 *
 * @author Vadim Emrich
 */
public class TimeSpanPanel extends javax.swing.JPanel implements ItemListener, ChangeListener {

    private class IterationItem {

        private IterationDTO iteration;

        public IterationItem(IterationDTO iteration) {
            this.iteration = iteration;
        }

        public IterationDTO getIteration() {
            return iteration;
        }

        @Override
        public String toString() {
            return iteration.getName();
        }
    }
    private IDialog dialog;
    private boolean canceled = true;
    private boolean listenToChange;
    private static final int TIMEDIFFERENCE = 500;

    /** Creates new form TimeSpanPanel */
    public TimeSpanPanel(List<IterationDTO> iterations) {
        initComponents();
        Date now = new Date();
        endTimeSpinner.getModel().setValue(now);
        endDateSpinner.getModel().setValue(now);
        startTimeSpinner.getModel().setValue(now);
        startDateSpinner.getModel().setValue(now);

        for (IterationDTO idto : iterations) {
            iterationComboBox.addItem(new IterationItem(idto));
        }

        iterationComboBox.addItemListener(this);
        startTimeSpinner.addChangeListener(this);
        startDateSpinner.addChangeListener(this);
        endTimeSpinner.addChangeListener(this);
        endDateSpinner.addChangeListener(this);
    }

    public void setDialog(IDialog dialog) {
        this.dialog = dialog;
    }

    public boolean wasCanceled() {
        return canceled;
    }

    public Date getStartDate() {
        Date startTime = ((SpinnerDateModel) startTimeSpinner.getModel()).getDate();
        Date startDate = ((SpinnerDateModel) startDateSpinner.getModel()).getDate();
        return combineDates(startTime, startDate);
    }

    public Date getEndDate() {
        Date endTime = ((SpinnerDateModel) endTimeSpinner.getModel()).getDate();
        Date endDate = ((SpinnerDateModel) endDateSpinner.getModel()).getDate();
        return combineDates(endTime, endDate);
    }

    private Date combineDates(Date time, Date date) {
        GregorianCalendar calTime = new GregorianCalendar();
        calTime.setTime(time);
        GregorianCalendar calDate = new GregorianCalendar();
        calDate.setTime(date);
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTimeInMillis(0l);
        cal.set(calDate.get(GregorianCalendar.YEAR), calDate.get(GregorianCalendar.MONTH), calDate.get(GregorianCalendar.DAY_OF_MONTH), calTime.get(GregorianCalendar.HOUR_OF_DAY), calTime.get(GregorianCalendar.MINUTE), calTime.get(GregorianCalendar.SECOND));
        return cal.getTime();
    }

    @Override
    public void itemStateChanged(ItemEvent e) {
        if (e.getStateChange() == ItemEvent.SELECTED) {
            try {
                IterationDTO selected = ((IterationItem) e.getItem()).getIteration();
                listenToChange = false;
                startTimeSpinner.setValue(selected.getStartDate());
                startDateSpinner.setValue(selected.getStartDate());
                endTimeSpinner.setValue(selected.getEndDate());
                endDateSpinner.setValue(selected.getEndDate());
                listenToChange = true;
            } catch (ClassCastException ex) {
                Logger.getLogger(TimeSpanPanel.class.getName()).log(Level.SEVERE, ex.getMessage());
            }
        }
    }

    @Override
    public void stateChanged(ChangeEvent e) {
        if (listenToChange) {
            iterationComboBox.setSelectedIndex(0);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("all")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        popupMenu1 = new java.awt.PopupMenu();
        finishButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        startTimePanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        startTimeSpinner = new javax.swing.JSpinner();
        startDateSpinner = new javax.swing.JSpinner();
        endTimePanel = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        endDateSpinner = new javax.swing.JSpinner();
        endTimeSpinner = new javax.swing.JSpinner();
        jPanel2 = new javax.swing.JPanel();
        iterationComboBox = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();

        popupMenu1.setLabel("popupMenu1");

        finishButton.setText("Finish");
        finishButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                finishButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        startTimePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Start Time"));
        startTimePanel.setPreferredSize(new java.awt.Dimension(225, 300));

        jLabel1.setText("Time:");

        jLabel2.setText("Date:");

        startTimeSpinner.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(), null, null, java.util.Calendar.MINUTE));
        startTimeSpinner.setEditor(new javax.swing.JSpinner.DateEditor(startTimeSpinner, "HH:mm:ss"));

        startDateSpinner.setModel(new javax.swing.SpinnerDateModel());
        startDateSpinner.setEditor(new javax.swing.JSpinner.DateEditor(startDateSpinner, "dd.MM.yyyy"));

        org.jdesktop.layout.GroupLayout startTimePanelLayout = new org.jdesktop.layout.GroupLayout(startTimePanel);
        startTimePanel.setLayout(startTimePanelLayout);
        startTimePanelLayout.setHorizontalGroup(
            startTimePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(startTimePanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(startTimePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel1)
                    .add(startTimeSpinner, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE)
                    .add(jLabel2)
                    .add(startDateSpinner, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE))
                .addContainerGap())
        );
        startTimePanelLayout.setVerticalGroup(
            startTimePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(startTimePanelLayout.createSequentialGroup()
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(startTimeSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel2)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(startDateSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        endTimePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("End Time"));
        endTimePanel.setPreferredSize(new java.awt.Dimension(225, 300));

        jLabel3.setText("Time:");

        jLabel4.setText("Date:");

        endDateSpinner.setModel(new javax.swing.SpinnerDateModel());
        endDateSpinner.setEditor(new javax.swing.JSpinner.DateEditor(endDateSpinner, "dd.MM.yyyy"));

        endTimeSpinner.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(), null, null, java.util.Calendar.MINUTE));
        endTimeSpinner.setEditor(new javax.swing.JSpinner.DateEditor(endTimeSpinner, "HH:mm:ss"));

        org.jdesktop.layout.GroupLayout endTimePanelLayout = new org.jdesktop.layout.GroupLayout(endTimePanel);
        endTimePanel.setLayout(endTimePanelLayout);
        endTimePanelLayout.setHorizontalGroup(
            endTimePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(endTimePanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(endTimePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel3)
                    .add(endTimeSpinner, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE)
                    .add(jLabel4)
                    .add(endDateSpinner, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE))
                .addContainerGap())
        );
        endTimePanelLayout.setVerticalGroup(
            endTimePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(endTimePanelLayout.createSequentialGroup()
                .add(jLabel3)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(endTimeSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel4)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(endDateSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(startTimePanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 200, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(endTimePanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 200, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(startTimePanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 160, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(endTimePanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 160, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(80, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Time Period", jPanel1);

        iterationComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "-" }));

        jLabel5.setText("Iteration:");

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel5)
                    .add(iterationComboBox, 0, 412, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .add(jLabel5)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(iterationComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(189, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Iteration", jPanel2);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap(281, Short.MAX_VALUE)
                .add(cancelButton)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(finishButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 86, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .add(jTabbedPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 470, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(jTabbedPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 286, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(finishButton)
                    .add(cancelButton)))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void finishButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_finishButtonActionPerformed
        evt.getID(); //to avoid unused formal paramter
        if (getStartDate().before(getEndDate())
                && Math.abs((getStartDate().getTime() - getEndDate().getTime())) > TIMEDIFFERENCE) {
            canceled = false;
            dialog.close();
        } else {
            ApplicationManager.instance().getViewManager().showMessageDialog(this,
                    "Start-date must be before the end-date!",
                    "Date Error",
                    JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_finishButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        evt.getID(); //to avoid unused formal paramter
        canceled = true;
        dialog.close();
    }//GEN-LAST:event_cancelButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JSpinner endDateSpinner;
    private javax.swing.JPanel endTimePanel;
    private javax.swing.JSpinner endTimeSpinner;
    private javax.swing.JButton finishButton;
    private javax.swing.JComboBox iterationComboBox;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTabbedPane jTabbedPane1;
    private java.awt.PopupMenu popupMenu1;
    private javax.swing.JSpinner startDateSpinner;
    private javax.swing.JPanel startTimePanel;
    private javax.swing.JSpinner startTimeSpinner;
    // End of variables declaration//GEN-END:variables
}
